<template>
<div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
        <el-form :inline="true" :model="filters" :size="size">
            <el-row class="search-input">
                <el-form-item label="品牌名称：">
                    <el-input v-model="filters.name" clearable placeholder="品牌名称" />
                </el-form-item>
                <el-form-item label="品牌来源：">
                  <el-select clearable v-model="filters.source" placeholder="品牌来源">
                    <!-- <el-option label="运营新增" value="1"></el-option>
                    <el-option label="商家新增" value="2"></el-option>
                    <el-option label="系统对接" value="3"></el-option> -->
                    <el-option
                        v-for="item in sourceList"
                        :key="item"
                        :label="item"
                        :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-row>
            <el-row class="search-button">
                <el-form-item>
                    <kt-button icon="fa fa-search" :label="$t('action.search')" type="primary" @click="findPage(null)" />
                </el-form-item>
                <el-form-item>
                    <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetForm('filters')" />
                </el-form-item>
                <el-form-item>
                    <kt-button icon="fa fa-plus" :label="$t('action.add')" type="primary" @click="handleAdd" />
                </el-form-item>
            </el-row>
        </el-form>
    </div>
    <!--表格内容栏-->
    <cy-table :height="350" :highlightCurrentRow="true" :content="pageResult" :totalSize="totalSize" :columns="columns" :showSelection="false" v-loading="loading" :showBatchDelete="false" @findPage="findPage" @handleEdit="handleEdit" @handleDetail="handleDetail" :showDetailOperation="true" :showDeleteOperation="false" ref="CyTable"></cy-table>
    <!--新增编辑界面-->
    <el-dialog :title="operation ? '新增' : '编辑'" width="60%" height="800px" :visible.sync="editDialogVisible" :close-on-click-modal="false">
        <el-form :model="dataForm" label-width="110px" :rules="dataFormRules" ref="dataForm" :size="size" :inline="true" :disabled="this.disabled">
            <el-row class="item30">
                <el-form-item label="ID：" prop="id" v-if="false">
                    <el-input v-model="dataForm.id" :disabled="true" auto-complete="off" placeholder="请输入ID"></el-input>
                </el-form-item>
                <el-form-item label="品牌名称：" prop="name">
                    <el-input v-model="dataForm.name" auto-complete="off" placeholder="请输入品牌名称"></el-input>
                </el-form-item>
                <el-form-item label="品牌别名：" prop="alias">
                    <el-input v-model="dataForm.alias" auto-complete="off" placeholder="请输入品牌别名"></el-input>
                </el-form-item>
                <el-form-item label="品牌所有：" prop="owner">
                    <el-input v-model="dataForm.owner" auto-complete="off" placeholder="请输入品牌所有"></el-input>
                </el-form-item>
                <el-form-item label="商标注册号：" prop="trademarkingNumber">
                    <el-input v-model="dataForm.trademarkingNumber" auto-complete="off" placeholder="请输入商标注册号"></el-input>
                </el-form-item>
                <el-form-item label="公司名称：" prop="companyName">
                    <el-input v-model="dataForm.companyName" auto-complete="off" placeholder="请输入公司名称"></el-input>
                </el-form-item>
                <el-row>
                    <el-form-item label="品牌logo：" prop="pic">
                        <el-upload :action="imgUpload" list-type="picture-card" :on-success="handlePicSuccess" v-model="dataForm.pic" :on-exceed="handleExceed" accept="image/gif, image/jpeg, image/jpg, image/png, image/svg" :on-remove="handlePicRemove" :limit="picLimit" style="float:left" ref="pic_upload" :file-list="picList" :disabled="this.disabled">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="资质证书" prop="certificate">
                        <el-upload :action="imgUpload" :on-success="handlCertificateSuccess" :on-exceed="handleCertificateExceed" list-type="picture-card" v-model="dataForm.pic" accept="image/gif, image/jpeg, image/jpg, image/png, image/svg" :on-remove="handleCertificateRemove" :limit="certificateLimit" style="float:left" ref="certificate_upload" :file-list="certificateList" :disabled="this.disabled">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                </el-row>
                <el-form-item label="公司介绍" prop="companyIntroduce">
                    <div>
                        <el-upload class="avatar-uploader" :action="imgUpload" multiple :on-success="uploadSuccess" :show-file-list="false" :disabled="this.disabled">
                        </el-upload>
                        <quill-editor v-model="dataForm.companyIntroduce" ref="myTextEditor" style="height: 250px;width: 850px;" :options="editorOption" :disabled="this.disabled"></quill-editor>
                    </div>
                </el-form-item>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 40px;">
            <el-button :size="size" @click.native="editDialogVisible = false" @click="clearFiles">{{ $t("action.cancel") }}
            </el-button>
            <el-button :size="size" type="primary" v-show="isSumbitShow" @click.native="submitForm" :loading="editLoading">{{ $t("action.submit") }}
            </el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
import CyTable from "@/views/Core/ProductTable";
import KtButton from "@/views/Core/KtButton";
import {
    quillEditor
} from "vue-quill-editor";
import * as Quill from "quill"; //引入编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{
        'header': 1
    }, {
        'header': 2
    }],
    [{
        'list': 'ordered'
    }, {
        'list': 'bullet'
    }],
    [{
        'script': 'sub'
    }, {
        'script': 'super'
    }],
    [{
        'indent': '-1'
    }, {
        'indent': '+1'
    }],
    [{
        'direction': 'rtl'
    }],
    [{
        'header': [1, 2, 3, 4, 5, 6, false]
    }],
    [{
        'color': []
    }, {
        'background': []
    }],
    [{
        'align': []
    }],
    ['link', 'image'],
    ['clean']
]
export default {
    components: {
        KtButton,
        CyTable,
        quillEditor
    },
    data() {
        return {
            sourceList: [],
            disabled: false,
            loading: true,
            picLimit: 1,
            certificateLimit: 3,
            isSumbitShow: true,
            editorOption: {
                theme: 'snow',
                boundary: document.body,
                modules: {
                    toolbar: {
                        container: toolbarOptions, //
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.avatar-uploader input').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    },
                },
                placeholder: '请输入协议内容',
                readOnly: false
            },
            imgUpload: this.utils.imgUploadUrl,
            sourceList: [{
                    key: 0,
                    source: "运营新增"
                },
                {
                    key: 1,
                    source: "商家新增"
                },
                {
                    key: 2,
                    source: "系统对接"
                }
            ],
            size: "small",
            filters: {
                name: "",
                source: ""
            },
            picList: [],
            totalSize: 0,
            pageResult: [],
            certificateList: [],
            columns: [{
                    prop: "name",
                    label: "品牌名称",
                    minWidth: 120
                },
                {
                    prop: "alias",
                    label: "品牌别名",
                    minWidth: 120
                },
                {
                    prop: "pic",
                    label: "品牌logo",
                    minWidth: 120,
                    showImg: true
                },
                {
                    prop: "source",
                    label: "品牌来源",
                    minWidth: 120
                },
                {
                    prop: "createTime",
                    label: "创建时间",
                    minWidth: 120
                }
            ],
            pageRequest: {
                pageNum: 1,
                pageSize: 10
            },
            filterColumns: [],
            editLoading: false,
            operation: false, // true:新增, false:编辑
            editDialogVisible: false, // 新增编辑界面是否显示
            dataFormRules: {
                name: [{
                    required: true,
                    message: "请输入品牌名称",
                    trigger: "blur"
                }]
            },
            // 新增编辑界面数据
            dataForm: {
                id: "",
                name: "",
                alias: "",
                pic: "",
                source: "",
                owner: "",
                trademarkingNumber: "",
                certificate: "",
                companyName: "",
                companyIntroduce: ""
            },
            // 图片上传
            dialogVisible: false
        };
    },
    mounted() {
        this.querySource();
    },
    methods: {
        //获取商品品牌中的所有品牌来源
        querySource: function() {
            let params = {};
            console.log("获取商品品牌中的所有品牌来源")
            var that = this;
            this.utils.request.querySource (params, function (res) {
            if (res.code === "0000") {
                var array=[];
                array = res.data;
                that.sourceList = array;
            }
            });
        },
        //富文本图片插入
        uploadSuccess(res, file) {
            // 首先获取富文本编辑器的实例
            let quill = this.$refs.myTextEditor.quill
            // 上传成功所执行
            if (res.code == "0000" && res.data !== null) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片res为服务器返回的数据
                quill.insertEmbed(length, 'image', res.data.imgUrl)
                // 光标移动至文本末端
                quill.setSelection(length + 1)
            } else {
                this.$message.error('图片插入失败')
            }
        },
        // 获取分页数据
        findPage: function (params) {
            let this_ = this;
            if (params == undefined || params == null) {
                params = {
                    pageNum: this_.pageRequest.pageNum,
                    pageSize: this_.pageRequest.pageSize
                };
            }
            if (this_.filters == undefined || this_.filters == null) {
                this_.filters = {};
            }
            this_.filters.start = params.pageNum;
            this_.filters.limit = params.pageSize;
            this.utils.request.queryPageProductBrand(this_.filters, function (res) {
                if (res.data.rows == null) {
                    res.data.rows = [];
                }
                this_.pageResult = res.data.rows;
                this_.totalSize = Number(res.data.total);
                this_.loading = false
            });
        },
        // 批量删除
        handleDelete: function (data) {
            var ids = "";
            for (var i = 0; i < data.params.length; i++) {
                ids = ids + data.params[i].id + ",";
            }
            data.params.t = "productBrand";
            data.params.ids = ids;
            this.utils.request.deleteUserInfo(data.params, data.callback);
        },
        // 显示新增界面
        handleAdd: function () {
            this.disabled = false;
            this.picList = [];
            this.certificateList = []
            this.editDialogVisible = true;
            this.operation = true;
            this.isSumbitShow = true;
            this.dataForm = {
                id: "",
                name: "",
                alias: "",
                pic: "",
                source: "",
                owner: "",
                trademarkingNumber: "",
                certificate: "",
                companyName: "",
                companyIntroduce: ""
            };

        },
        // 显示编辑界面
        handleEdit: function (params) {
            this.disabled = false;
            this.editDialogVisible = true;
            this.operation = false;
            this.isSumbitShow = true;
            this.$nextTick(function () {
                this.dataForm = Object.assign({}, params.row);
            });
            this.picList = [];
            let imgUrl = {};
            if (params.row.pic != null && params.row.pic != "") {
                imgUrl.url = params.row.pic;
                this.picList.push(imgUrl);
            }
            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
            this.certificateList = [];
            if (params.row.certificate != null && params.row.certificate != "") {
                let imgUrlArray = params.row.certificate.split(",");
                imgUrlArray.forEach(item => {
                    if (item != "") {
                        let imgUrl = {};
                        imgUrl.url = item;
                        this.certificateList.push(imgUrl);
                    }
                });
            }
        },
        // 编辑
        submitForm: function () {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    this.$confirm("确认提交吗？", "提示", {}).then(() => {
                        if (this.dataForm.companyIntroduce != "") {
                            this.dataForm.companyIntroduce = this.dataForm.companyIntroduce.replace(
                                /%/g,
                                "%25"
                            );
                        }
                        if (this.certificateList.length > 0) {
                            this.dataForm.certificate = "";
                            this.certificateList.forEach(item => {
                                this.dataForm.certificate += item.url + ",";
                            });
                        }
                        let params = Object.assign({}, this.dataForm);
                        var this_ = this;
                        this.utils.request.editProductBrand(params, function (res) {
                            if (res.code == "0000") {
                                this_.$message({
                                    message: "操作成功",
                                    type: "success"
                                });
                                this_.$refs["dataForm"].resetFields();
                                this_.editDialogVisible = false;
                                this_.findPage(null);
                            } else {
                                this_.$message({
                                    message: "操作失败, " + res.msg,
                                    type: "error"
                                });
                            }
                        });
                    });
                }
            });
        },
        // 详情
        handleDetail: function (params) {
            this.disabled = true;
            this.editDialogVisible = true;
            this.operation = false;
            this.isSumbitShow = false;
            this.$nextTick(function () {
                this.dataForm = Object.assign({}, params.row);
            });
            this.picList = [];
            let imgUrl = {};
            if (params.row.pic != null && params.row.pic != "") {
                imgUrl.url = params.row.pic;
                this.picList.push(imgUrl);
            }
            this.certificateList = [];
            if (params.row.certificate != null && params.row.certificate != "") {
                let imgUrlArray = params.row.certificate.split(",");
                imgUrlArray.forEach(item => {
                    if (item != "") {
                        let imgUrl = {};
                        imgUrl.url = item;
                        this.certificateList.push(imgUrl);
                    }
                });
            }
            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
        },

        // 重置
        resetForm(formName) {
            this.filters = {
                name: "",
                shop_id: "",
                status: ""
            };
            this.findPage();
        },

        // logo上传
        handlePicSuccess: function (res, file) {
            if (res.code == "0000") {
                this.dataForm.pic = res.data.imgUrl;
                let imgUrl = {};
                imgUrl.url = res.data.imgUrl;
                this.picList.push(imgUrl);
            }
        },
        //文件上传数量限制
        handleExceed: function () {
            this.$alert("最多上传一个", "警告", {
                confirmButtonText: "确定"
            });
        },
        //文件移除
        handlePicRemove(file, picList) {
            if (picList && picList.length == 0) {
                this.dataForm.pic = "";
            }
            this.picList = picList
        },
        // 资质上传
        handlCertificateSuccess(res, file) {
            if (res.code == "0000") {
                let imgUrl = {};
                imgUrl.url = res.data.imgUrl;
                this.certificateList.push(imgUrl);
            }
        },
        //文件上传数量限制
        handleCertificateExceed: function () {
            this.$alert("最多上传三个", "警告", {
                confirmButtonText: "确定"
            });
        },
        handleCertificateRemove(file, certificateList, index) {
            this.certificateList = certificateList;
        },
        clearFiles() {
            this.$refs["certificate_upload"].clearFiles();
            this.$refs["pic_upload"].clearFiles();
        }
    }
};
</script>

<style scoped lang='scss'>

</style>
